package com.i2863.tools.weixinmp.util;

import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * http代理工具类
 *
 * Created by xuweiwei on 2017/2/21.
 *
 */
public class SunProxyUtil {
    /**
     * 代理队列
     */
    private static ConcurrentLinkedQueue<HttpHost> httpProxyQueue = new ConcurrentLinkedQueue();
    /**
     * https代理队列
     */
    private static ConcurrentLinkedQueue<HttpHost> httpsProxyQueue = new ConcurrentLinkedQueue();


    private static CloseableHttpClient httpClient = HttpSessionUtils.buildHttpClient();

    private static Logger logger = LoggerFactory.getLogger(SunProxyUtil.class);

    public static void loadProxy(){
        String url ="http://http-api.taiyangruanjian.com/getip?num=5&type=1&pro=&city=0&yys=0&port=1&pack=2934&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=";
        loadProxy(url,httpProxyQueue);
    }
    public static void loadHttpsProxy(){
        String url = "http://http-api.taiyangruanjian.com/getip?num=5&type=1&pro=&city=0&yys=0&port=11&pack=2934&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=";
        loadProxy(url,httpsProxyQueue);
    }

    /**
     * 请求代理提供商网站,获取代理地址.
     */
    public static void loadProxy(String url,ConcurrentLinkedQueue<HttpHost> queue) {
        try {
            String result = HttpSessionUtils.httpGet(httpClient, url);
            String[] lines = result.split("\r\n");
            for (String line : lines) {
                //代理地址格式 host:port 或 host ,第二种使用默认80端口
                try {
                    String[] hostAndPort = line.split(":");
                    if (hostAndPort.length == 2) {
                        HttpHost host = new HttpHost(hostAndPort[0].trim(), Integer.parseInt(hostAndPort[1].trim()));
                        queue.add(host);
                    } else if (hostAndPort.length == 1) {
                        HttpHost host = new HttpHost(hostAndPort[0].trim(), 80);
                        queue.add(host);
                    } else {
                        logger.error("无效的http代理:{}", line);
                    }
                } catch (Exception e) {
                    logger.error("http代理地址解析异常", e);
                }
            }

        } catch (Exception e) {
            logger.error("加载http代理异常", e);
        }
    }

    /**
     * 获取代理,如果代理缓存为0,去代理网站获取新的代理放到缓存中
     *
     * @return Http代理
     */
    public synchronized static HttpHost getHttpHost(String url) {
        HttpHost proxy = null;
        if(url!=null && url.startsWith("https")){
            if(httpsProxyQueue.isEmpty()){
                //加载https代理
                loadHttpsProxy();
            }
            proxy =  httpsProxyQueue.poll();
        }else{
            if (httpProxyQueue.isEmpty()) {
                //加载http代理
                loadProxy();
            }
            proxy =  httpProxyQueue.poll();
        }
        if(proxy==null){
            throw new NullPointerException("proxy =null");
        }
        return proxy;
    }


    public static void main(String[] args) {
        HttpHost host1 = getHttpHost("https://www.baidu.com");
        HttpHost host2 = getHttpHost("http://www.baidu.com");
        System.out.println(host1);
        System.out.println(host2);
    }

}
